import threading
import Queue
import time
class Worker(threading.Thread):
    work_queue = Queue.Queue()
    def __init__(self, name):
        threading.Thread.__init__(self)
        self.setDaemon(True)
        self.th_pool = []
        self.add_th()
        self.result = True
        self.name = name
        self.__stop_event = threading.Event()

    def add_th(self):
        for th in range(3):
            th = threading.Thread(target = self.f)
            th.daemon = True
            self.th_pool.append(th)
            th.start()

    def f(self):
        while True:
            print 
            job = self.work_queue.get(True)
            print "thread name: ", self.name, threading.current_thread().name, job
            if job == 3:
                self.result = False
                print "thread name: ", self.name, "error happen"
                break
            if job == None:
                break
            time.sleep(4)

        print threading.current_thread().name, "Finshed"

    def join(self, timeout = None):
        if timeout != None:
            deadline = time.time() + timeout

        while True:
            print "join"
            print  self.th_pool
            if self.result == False:
                print "worker error happen"
                self.stop()
                raise Exception("Error happen")
                break
            for th in self.th_pool:
                th.join(1)
                if not th.isAlive():
                   self.th_pool.remove(th)
            if self.th_pool == []:
                break
            if timeout != None and time.time() - deadline <= 0:
                print "thread name: ", self.name, "timeout"
                break
    
    def stop(self):
        print "thread name: ", self.name, "stop"
        self.__stop_event.set()            
    



worker1 = Worker("1")
worker_pool = []

for i in range(15):
    worker1.work_queue.put(i)
for i in range(3):
    worker1.work_queue.put(None)

worker_pool.append(worker1)

for worker in worker_pool:
    worker.start()
try:
    while True:
        for worker in worker_pool:
            worker.join(5)
            if not worker.isAlive():
                print "worker not isAlive"
                worker_pool.remove(worker)
        if worker_pool == []:
            break

except Exception, e:
    print "error message", e
    print "stop thread"
    for worker in worker_pool:
        worker.stop()
        worker.join()
    print "total finshed"
